import cv2

# 视频输入
cap1 = cv2.VideoCapture("video1.mp4")
cap2 = cv2.VideoCapture("video2.mp4")
cap3 = cv2.VideoCapture("video3.mp4")

# 获取帧宽高，用于后续初始化输出
frame_width = int(cap1.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap1.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap1.get(cv2.CAP_PROP_FPS)
frame_count = int(min(cap1.get(cv2.CAP_PROP_FRAME_COUNT),
                      cap2.get(cv2.CAP_PROP_FRAME_COUNT),
                      cap3.get(cv2.CAP_PROP_FRAME_COUNT)))

# 输出视频设置
out = cv2.VideoWriter("panorama_output.mp4",
                      cv2.VideoWriter_fourcc(*'mp4v'),
                      fps, (frame_width * 3, frame_height))

# 创建拼接器（OpenCV 4.5+）
stitcher = cv2.Stitcher_create(cv2.Stitcher_PANORAMA)

for i in range(frame_count):
    ret1, frame1 = cap1.read()
    ret2, frame2 = cap2.read()
    ret3, frame3 = cap3.read()

    if not (ret1 and ret2 and ret3):
        break

    # 可选择resize保证大小一致
    frame1 = cv2.resize(frame1, (frame_width, frame_height))
    frame2 = cv2.resize(frame2, (frame_width, frame_height))
    frame3 = cv2.resize(frame3, (frame_width, frame_height))

    # 拼接成全景图
    status, pano = stitcher.stitch([frame1, frame2, frame3])

    if status == cv2.Stitcher_OK:
        pano_resized = cv2.resize(pano, (frame_width * 3, frame_height))
        out.write(pano_resized)
        print(f"帧 {i+1}/{frame_count} 拼接成功")
    else:
        print(f"帧 {i+1} 拼接失败")
        continue

cap1.release()
cap2.release()
cap3.release()
out.release()
cv2.destroyAllWindows()
print("全景视频已保存为 panorama_output.mp4")
